package com.last.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.last.jwt.util.JwtUtils;
import com.last.jwt.util.RsaUtils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 如果是登录请求，必须放行
        URI uri = request.getURI();
        //  对登录过滤
        if (uri.getPath().indexOf("login")>0 ||
                uri.getPath().indexOf("search")>0 ||
                uri.getPath().indexOf("homestaySearch")>0 ||
                uri.getPath().indexOf("notify")>0 ||
                uri.getPath().indexOf("upload")>0||
                uri.getPath().indexOf("websocket")>0
        ) {
           return chain.filter(exchange);
        }
        // 获取jwt令牌
        String jwtToken = exchange.getRequest().getHeaders().getFirst("token");
        if (jwtToken == null) {
            // token为空时，直接返回，并提示
            Map res = new HashMap(){{
                put("success",false);
                put("msg","你还未登录");
            }};
           return response(response, res );
        }else{
            // 令牌不为空时，需要登录认证
            PublicKey publicKey = null;
            try {
                // 加载公钥
                publicKey = RsaUtils.getPublicKey(
                        ResourceUtils.getFile("classpath:ras_public").getPath());
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                // 解析令牌，获取用户信息存入map
                Map infoFromToken = (Map) JwtUtils.getInfoFromToken(jwtToken, publicKey, Map.class);

                // 将用户信息向下传递，把用户的id放入头部，后面的采用拦截器的方式获取
                ServerHttpRequest mutableReq = request.mutate().header("userId", ""+ infoFromToken.get("userId")).build();
                ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
                //  放行
                return chain.filter(mutableExchange);
            }catch (MalformedJwtException ex){
                // jwt解析异常
                Map res = new HashMap(){{
                    put("success",false);
                    put("msg","jwt令牌不合法");
                }};
                return response(response, res );

            }catch (ExpiredJwtException exception){
                Map res = new HashMap(){{
                    put("success",false);
                    put("msg","jwt令牌过期");
                }};
                return response(response, res );
            }
        }
    }
    //指定过滤器的执行顺序，值越小越先执行
    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> response(ServerHttpResponse response, Map res){
        //不能放行，直接返回，返回json信息
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = null;
        try {
            jsonStr = objectMapper.writeValueAsString(res);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        DataBuffer dataBuffer = response.bufferFactory().wrap(jsonStr.getBytes());
        return response.writeWith(Flux.just(dataBuffer));// 响应json数据
    }
}